package com.wdzl.controller;

import com.wdzl.pojo.Percent;
import com.wdzl.service.PercentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
public class FileController {
    @Autowired
    private PercentService percentService;
    @RequestMapping("files/{id}")
    public String a(@PathVariable("id") Integer id, HttpServletRequest request, Model model, MultipartFile file) throws IOException {
String localpath="D:\\SSM\\work02\\target\\work02\\WEB-INF\\image\\";
        String sqlPath = null;
        System.out.println (file);
        String filename=null;
        if(!file.isEmpty()){
            //生成uuid作为文件名称
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            //获得文件类型（可以判断如果不是图片，禁止上传）
            String contentType=file.getContentType();
            //获得文件后缀名
            String suffixName=contentType.substring(contentType.indexOf("/")+1);
            //得到 文件名
            filename=uuid+"."+suffixName;
            //文件保存路径
            file.transferTo (new File (localpath+filename));
        }
        //把图片的相对路径保存至数据库
        sqlPath =filename;
        System.out.println(sqlPath);
        Percent percent=new Percent ();
        percent.setImage (sqlPath);
        percent.setId (id);
        percentService.update (percent);
//        user.setImage(sqlPath);
//        userService.addUser(user);
//        model.addAttribute("user", user);
        return "redirect:/percent/list";
    }
}

